<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row>
        <el-col>
          选择商品分类：
          <el-cascader
            expand-trigger="hover"
            :options="cateList"
            :props="cateProps"
            v-model="cateKeys"
            @change="handleChange"
          >
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane
          :label="item.tabLabel"
          :name="item.tabName"
          v-for="(item, index) in tabsData"
          :key="index"
        >
          <el-button
            size="mini"
            type="primary"
            :disabled="isdisabled"
            @click="showAddEditClick('add')"
            >添加参数</el-button
          >
          <el-table :data="paramsList">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="paramsClose(scope.row, index)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showAddEditClick('edit', scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete "
                  @click="deleteParam(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :title="addEditTitle + addEditLabel"
      :visible.sync="addEditDialogVisible"
      width="50%"
      @close="addEditClose"
    >
      <el-form
        :model="addEditForm"
        :rules="addEditFormRules"
        ref="addEditFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="addEditLabel" prop="attr_name">
          <el-input v-model="addEditForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addEditClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      cateList: [],
      cateKeys: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      tabsData: [
        { tabLabel: '动态参数', tabName: 'many' },
        { tabLabel: '静态属性', tabName: 'only' }
      ],
      paramsList: [],
      addEditDialogVisible: false,
      addEditType: '',
      addEditForm: {
        attr_name: ''
      },
      addEditFormRules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类失败！')
      this.cateList = res.data
    },
    handleChange () {
      this.getParamsList()
    },
    handleClick () {
      console.log(this.activeName)
      this.getParamsList()
    },
    async getParamsList () {
      if (this.cateKeys.length !== 3) {
        this.cateKeys = []
        this.paramsList = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败！')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res)
      this.paramsList = res.data
    },
    async showAddEditClick (type, id) {
      this.addEditType = type
      this.addEditForm.attr_name = ''
      if (type === 'edit') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, { params: { attr_sel: this.activeName } })
        if (res.meta.status !== 200) return this.$message.error('查询参数失败！')
        this.addEditForm = res.data
      }
      this.addEditDialogVisible = true
    },
    addEditClick () {
      this.$refs.addEditFormRef.validate(async valid => {
        if (!valid) return
        if (this.addEditType === 'add') {
          const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_name: this.addEditForm.attr_name, attr_sel: this.activeName })
          if (res.meta.status !== 201) return this.$message.error('添加参数失败！')
          this.$message.success('添加参数成功！')
        } else if (this.addEditType === 'edit') {
          const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.addEditForm.attr_id}`, { attr_name: this.addEditForm.attr_name, attr_sel: this.activeName })
          if (res.meta.status !== 200) return this.$message.error('修改参数失败！')
          this.$message.success('修改参数成功！')
        }
        this.getParamsList()
        this.addEditDialogVisible = false
      })
    },
    addEditClose () {
      this.$refs.addEditFormRef.resetFields()
    },
    async deleteParam (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message('已取消删除！')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除参数失败！')
      this.$message.success('删除参加成功！')
      this.getParamsList()
    },
    async setParams (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: this.activeName, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) return this.$message.error('更新参数失败！')
      this.$message.success('更新参数成功！')
    },
    handleInputConfirm (row) {
      if (row.inputValue.trim().length > 0) {
        row.attr_vals.push(row.inputValue.trim())
        this.setParams(row)
      }
      row.inputValue = ''
      row.inputVisible = false
    },
    paramsClose (row, index) {
      row.attr_vals.splice(index, 1)
      this.setParams(row)
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        console.log(this.$refs.saveTagInput)
        this.$refs.saveTagInput[0].$refs.input.focus()
      })
    }
  },
  computed: {
    isdisabled () {
      return this.cateKeys.length !== 3
    },
    cateId () {
      return this.cateKeys.length === 3 ? this.cateKeys[2] : null
    },
    addEditLabel () {
      return this.activeName === 'many' ? '参数名称' : '静态属性'
    },
    addEditTitle () {
      return this.addEditType === 'edit' ? '修改' : '添加'
    }
  }
}
</script>
<style scoped>
.el-col {
  margin: 15px 0;
}
.el-tag {
  margin: 8px;
}
.input-new-tag {
  width: 120px;
}
</style>
